iT邦幫忙

2025 iThome 鐵人賽

DAY 23
0
Vue.js

Vue 新手學習紀錄系列 第 23

Day 25|Vue Transition

  • 分享至 

  • xImage
  •  

Vue 提供的 <transition> 元件,能讓元素進出畫面時自動套用動畫效果,不用額外的 JS,只須加上 class 名稱就能做到

相對應 class 名稱

  • v-enter-from
    • 元素剛被插入,但還沒顯示。
    • 可設定起始狀態(例如透明度 0、縮放 0.8)。
  • v-enter-active
    • 元素進入中的過程。
    • 用來設定 transition 動畫時間與曲線。
  • v-enter-to
    • 元素已經完全顯示。
    • 最終狀態(例如透明度 1)。
  • v-leave-from
    • 元素準備消失。
    • 動畫的起始狀態。
  • v-leave-active
    • 離開動畫執行中。
    • 設定 transition 時間、曲線。
  • v-leave-to
    • 元素即將被移除。
    • 動畫結束狀態(例如透明度 0、縮放 0.8)。

基本範例

<template>
  <button @click="show = !show">切換</button>

  <transition name="fade">
    <p v-if="show" class="box">Hello Vue!</p>
  </transition>
</template>

<script setup>
import { ref } from 'vue'
const show = ref(true)
</script>

<style scoped>
.fade-enter-from, .fade-leave-to {
  opacity: 0;
}
.fade-enter-to, .fade-leave-from {
  opacity: 1;
}
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.5s ease;
}
.box {
  background: #f4f4f4;
  padding: 1rem;
  border-radius: 8px;
}
</style>
  • 切換到 show 時,這段文字就會淡入/淡出

Transition Group

對多個元素同時套用動畫,範例如下:

<template>
  <button @click="addItem">新增項目</button>

  <transition-group name="list" tag="ul">
    <li v-for="item in items" :key="item" class="list-item">
      {{ item }}
    </li>
  </transition-group>
</template>

<script setup>
import { ref } from 'vue'
const items = ref(['台大資管', '政大資管'])
function addItem() {
  items.value.push('清大資工')
}
</script>

<style scoped>
.list-item {
  margin: 4px 0;
  padding: 8px;
  background: #f9f9f9;
  border-radius: 6px;
}

.list-enter-active, .list-leave-active {
  transition: all 0.4s ease;
}
.list-enter-from, .list-leave-to {
  opacity: 0;
  transform: translateY(20px);
}
</style>

小結

  • transition 動畫使用
  • transition-group 群組動畫使用

上一篇
Day 22 | 自定義指令
下一篇
Day 24 | v-model 雙向綁定
系列文
Vue 新手學習紀錄24
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言